import React, { useState, useRef, useCallback } from 'react'
import { connect } from 'react-redux'
import { adddataAction } from '../actions'
function TodoInput(props) {
    const [inputValue, setInputValue] = useState('')

    const inputRef = useRef('')
    //添加代办事项
    const adddata = useCallback(() => {
        props.addData(inputValue)
        setInputValue('')
        inputRef.current.focus()


    }, [inputValue])
    // 抬起
    const handleKeyup = e => {
        if (e.key.toLowerCase() === 'enter') {
            adddata()
        }
    }

    // 输入框值改变
    const handleChange = useCallback((e) => {
        setInputValue(e.target.value)

    }, [inputValue])
    return (
        <>
            <div className='todo-input container'>
                <div className="field is-grouped">
                    <p className="control is-expanded">
                        <input
                            className="input"
                            type="text"
                            placeholder="请输入新待办事项"
                            value={inputValue}
                            ref={inputRef}
                            onChange={handleChange}
                            onKeyUp={handleKeyup}

                        />
                    </p>
                    <p className="control">
                        <i className="button is-primary" onClick={adddata}>
                            添加
                        </i>
                    </p>
                </div>
            </div>
        </>
    )
}
const mapDispatchToProps = dispatch => (
    {
        addData(title) {
            dispatch(adddataAction(title))
        }
    }
)
export default connect(null, mapDispatchToProps)(TodoInput)

